<template>
	<view class="page tn-safe-area-inset-bottom" :style="{paddingTop: vuex_custom_bar_height + 'px'}">
		<view class="top-bg"></view>
		<dawnBar title="订单信息"></dawnBar>
		<view class="page-container">
			<view v-if="orderInfo.orderNumber">

				<view class="list tn-margin-top-sm" v-if="orderInfo.orderName === '预约挂号'">
					<view class="list-item">
						<view class="list-head tn-flex tn-flex-direction-row tn-flex-col-center tn-flex-row-between">
							<view class="tn-flex tn-flex-direction-row tn-flex-col-center tn-flex-row-between">
								<text
									class="dawn-text-md tn-text-bold tn-color-dawn">{{orderInfo.billMap.departmentName || '' }}</text>
								<text class="tn-color-gray tn-padding-left-xs tn-padding-right-xs">|</text>
								<tn-tag class="dawn-tag-sm dawn-tag-sm__2">{{orderInfo.billMap.regDate || '' }}</tn-tag>
							</view>
							<view>
								<view class="justify-content-item ">
									<tn-tag backgroundColor="tn-main-gradient-dawn" fontColor="#FFFFFF"
										shape="circleLeft" width="auto">
										{{ orderInfo.billMap.regType || ''}}
									</tn-tag>
								</view>
							</view>
						</view>
						<view class="list-content tn-flex tn-flex-col-center tn-flex-row-between">
							<view class="tn-flex tn-flex-col-center tn-flex-row-left">
								<view class="tn-flex tn-flex-col-center">
									<!-- <tn-avatar shape="square" :text="orderInfo.name" size="130rpx"></tn-avatar> -->
									<image mode="aspectFill" class="doctor-image"
										src="../../static/images/icon_yygh.png">
								</view>
								<view class="tn-padding-left-ss">
									<view class="">
										<text
											class="dawn-text-md tn-text-bold tn-color-dawn tn-margin-right-ss">{{orderInfo.billMap.doctorName || '' }}</text>
									</view>
									<view class="">
										<text class="dawn-text-sm tn-margin-right-ss">就诊日期</text>
										<text class="dawn-text-sm tn-text-bold">{{ orderInfo.billMap.regDate }}</text>
									</view>
									<view class="">
										<text class="dawn-text-sm tn-margin-right-ss">就诊时间</text>
										<text
											class="dawn-text-sm tn-text-bold">{{ orderInfo.billMap.scheduleTime }}</text>
									</view>
								</view>
							</view>
							<view class="tn-flex tn-flex-nowrap  tn-flex-col-center tn-flex-row-left">
								<view class="justify-content-item tn-text-right">
									<text class="tn-icon-right tn-color-gray"></text>
								</view>
							</view>
						</view>
						<!-- <view class="dawn-line tn-margin-top-sm"></view> -->
					</view>
				</view>


				<view class="tn-bg-white dawn-shadow tn-padding dawn-radius tn-margin-top-sm">
					<view class="list-text">
						<view class="list__left">
							<view class="list__left__text">缴费商户</view>
						</view>
						<view class="list__right list-text__right">
							{{appConfig.appTitle || '' }}
						</view>
					</view>
					<view class="list-text">
						<view class="list__left">
							<view class="list__left__text">缴费业务</view>
						</view>
						<view class="list__right list-text__right">
							<tn-tag class="dawn-tag-sm dawn-tag-sm__4">{{ orderInfo.orderName  || '' }}</tn-tag>
						</view>
					</view>
					<view class="list-text">
						<view class="list__left">
							<view class="list__left__text">订单号</view>
						</view>
						<view class="list__right list-text__right">
							{{ orderInfo.orderNumber }}
						</view>
					</view>
					<view class="list-text">
						<view class="list__left">
							<view class="list__left__text">身份证</view>
						</view>
						<view class="list__right list-text__right">
							{{ patientInfo.cardNo_  || '' }}
						</view>
					</view>
				</view>

				<view class="list-item tn-main-gradient-dawn tn-margin-top-sm">
					<view class="tn-flex tn-flex-nowrap tn-flex-col-center tn-flex-row-between">
						<view>
							<view class="tn-color-white">
								<text>订单金额</text>
							</view>
							<view class="tn-color-white tn-padding-top">
								<text style="margin-left: -6rpx;">￥</text>
								<text class="tn-text-bold" style="font-size: 55rpx;">{{ orderInfo.totalCost }}</text>
							</view>
						</view>
						<view>
							<view class="tn-color-white">
								<view class="tn-padding-bottom-sm">
									<text class="tn-padding-right-xs"
										style="padding-left: 30rpx;opacity: 0.7;">姓名</text>
									{{ patientInfo.name_ }}
								</view>
								<view class="tn-padding-bottom-sm">
									<text class="tn-padding-right-xs" style="opacity: 0.7;">患者ID</text>
									{{ patientInfo.patientId }}
								</view>
								<view class="tn-padding-bottom-sm">
									<text class="tn-padding-right-xs" style="opacity: 0.7;">门诊号</text>
									{{ patientInfo.clinicNo }}
								</view>

							</view>
						</view>
					</view>
					<view class="dawn-line tn-margin-top-sm"></view>
					<view class=" tn-flex tn-flex-direction-row tn-flex-nowrap tn-flex-col-center tn-flex-row-between">
						<view class="justify-content-item tn-text-df">
							<!-- <text class="tn-icon-time-fill tn-color-black"></text> -->
							<!-- <text class="tn-color-black">{{ formatDateTime(orderInfo.YYSJ)  || '' }}</text> -->
						</view>
						<view
							class="tn-flex tn-flex-direction-row tn-flex-nowrap tn-flex-col-center tn-flex-row-right op-box">
							<!-- <tn-button @click="navDteail(item)" size="sm" class="dawn-btn-sm dawn-btn-sm__primary">
								<text class="tn-icon-send-fill">缴费</text>
							</tn-button> -->
						</view>
					</view>
				</view>

				<view class="tn-padding-sm tn-margin-top-xl">
					<view class="tn-margin-bottom ">
						<text class="dawn-text-lg tn-color-dawn tn-text-bold">请选择支付方式</text>
					</view>
					<view class="list-icon-text" @click="payType = 'PAY_WX_JSAIPI'">
						<view class="list__left">
							<image class="list__left__image" src="../../static/images/icon_pay_wx.png" mode="aspectFit">
							</image>
							<view class="list__left__text" style="color: black;">微信支付</view>
						</view>
						<view class="list__right">
							<tn-radio-group v-model="payType">
								<tn-radio :size="size" :iconSize="iconSize" shape="square" borderColor="#43c93e"
									name="PAY_WX_JSAIPI" activeColor="#43c93e"></tn-radio>
							</tn-radio-group>
						</view>
					</view>
					<view class="list-icon-text" @click="payType = 'PAY_WX_CHS'" v-if="orderInfo.orderName === 'chs'">
						<view class="list__left">
							<image class="list__left__image" src="../../static/images/icon_chs.png" mode="aspectFit">
							</image>
							<view class="list__left__text" style="color: black;">医保移动支付</view>
						</view>
						<view class="list__right">
							<tn-radio-group v-model="payType">
								<tn-radio :size="size" :iconSize="iconSize" shape="square" name="PAY_WX_CHS"
									activeColor="#299dd9" borderColor="#299dd9"></tn-radio>
							</tn-radio-group>
						</view>
					</view>

				</view>
				
				<view class="tn-margin-top-xl tn-text-center dawn-text-md">
					<text >订单剩余支付时间</text>
					<text class="dawn-text-lg dawn-color-red tn-padding-left-xs tn-padding-right-xs">{{ countdown }}</text>
					<text >秒</text>
				</view>

				<!-- 悬浮按钮-->
				<view class="tn-flex tn-footerfixed">
					<view class="tn-flex-1 justify-content-item tn-margin-sm tn-text-center">
						<tn-button @click="onPay" class="dawn-btn-lg" backgroundColor="tn-main-gradient-dawn">
							<text class="tn-icon-money tn-padding-right-xs"></text>
							<text>确认支付</text>
						</tn-button>
					</view>
				</view>

			</view>
			<view v-if="show">
				<dawnMsg :box="dawnMsgBox" :msg="msg"></dawnMsg>
			</view>
		</view>


		<tn-landscape :show="showChs" :closeBtn="false" :mask="true" :maskCloseable="false">
			<image style="width:120px;height: 120rpx;border-radius: 40%;" mode="widthFix"
				src="../../static/images/icon_chs_loading.gif">
			</image>
			<view class="tn-margin-top">
				<text class="chs-loading-text">正在处理中，请稍候...</text>
			</view>
		</tn-landscape>

		<!-- loading -->
		<dawnLoading :show="loading"></dawnLoading>

		<!-- 悬浮按钮-->
		<NavBtn></NavBtn>
	</view>
</template>

<script>
	import page_mixin from '@/mixins/page_mixin.js'
	import dayjs from '@/plugin/dayjs/dayjs.min.js';
	import * as PayApi from "@/api/hospital/pay.js";
	import * as ChsApi from "@/api/hospital/chs.js";
	import * as api from '@/api/api.js';
	import * as config from "@/api/config.js";

	import chs from "@/libs/chs.js";
	import {
		toLogin
	} from '@/libs/login.js';
	import {
		mapGetters
	} from "vuex";
	const app = getApp();

	export default {
		name: 'order',
		mixins: [page_mixin],
		computed: mapGetters(['appConfig', 'uid', 'isLogin', 'userInfo', 'patientInfo']),
		data() {
			return {
				iconSize: 38,
				size: 40,
				loading: false,
				showChs: false,
				show: false,
				msg: '',
				dawnMsgBox: '',
				tabsIndex: 0,
				queryData: {
					pageSize: 10,
					pageNo: 1,
					patientId: '',
					patientName: '',
					orderNumber: ''
				},
				// 支付方式 PAY_WX_JSAIPI PAY_WX_CHS PAY_ALI_JSAIPI
				payType: 'PAY_WX_JSAIPI',
				status: -1,
				auth: {},
				authInfo: {},
				orderInfo: {},
				chsPass: {},
				countdown: 120  // 初始倒计时时间设置为120秒
			}
		},
		async onLoad(options) {
			await this.$onLaunched;
			console.info("order info options");
			console.table(options);
			if (!this.isLogin) {
				toLogin();
				return;
			} else {
				let that = this;
				if (options.hasOwnProperty('retCode')) {
					this.auth = options;
				}
				this.queryData.orderNumber = options.orderNumber;
				this.queryData.pid = this.patientInfo.id;
				this.queryData.userId = this.patientInfo.openid;
				this.queryData.patientId = this.patientInfo.patientId;
				this.queryData.patientName = this.patientInfo.name;
				this.getPaySignData();
				this.startCountdown();
			}
		},
		methods: {
			initData() {
				api.getConfigByKey(config.CONFIG_TYPE.CHS_PASS).then(res => {
					console.table(res);
					if (res.code === 0) {
						this.chsPass = res.data;
					}
				}).catch(err => {

				})
			},
			startCountdown: function() {
				const timer = setInterval(() => {
					if (this.countdown > 0) {
						this.countdown--; // 每秒减1
					} else {
						clearInterval(timer); // 倒计时结束，清除定时器
						uni.switchTab({
							url: '/main/index/index'
						});
					}
				}, 1000);
			},
			toChsOauthUser: function() {
				let that = this;
				that.payType = 'PAY_WX_CHS';
				const retCode = that.auth.retCode;
				if (retCode === '0') {
					// that.loading = true;
					this.showChs = true;
					this.show = false;
					this.dawnMsgBox = 'popup';
					this.msg = '';

					const queryChsData = new Object();
					queryChsData.userId = that.patientInfo.id;
					queryChsData.patientId = that.patientInfo.patientId;
					queryChsData.patientName = that.patientInfo.name;

					queryChsData.orderNumber = that.queryData.orderNumber;
					queryChsData.authCode = that.auth.authCode;
					queryChsData.openid = that.auth.openid;
					ChsApi.oauthUserQuery(queryChsData).then(res => {
						that.showChs = false;
						// that.loading = false;
						if (res.code === 0) {
							uni.showToast({
								title: '获取用户医保信息成功',
								icon: 'none'
							})
							that.authInfo = res.data;
							that.toChsOrder();
						} else {
							that.show = true;
							that.msg = '获取用户医保信息失败=>' + res.msg;
						}
					}).catch(error => {
						console.table(error);
						// that.loading = false;
						that.showChs = false;
						that.show = true;
						that.msg = '获取用户医保信息失败=>' + error.message;
					});
				} else if (retCode === '150402') {
					that.show = true;
					that.msg = '用户未激活电子凭证';
					that.showChs = false;
					that.loading = false;
				} else if (retCode === '150403') {
					// that.show = true;
					// that.msg = '用户取消授权';
				} else {
					that.showChs = false;
					that.loading = false;
				}
			},
			toChsOrder: function() {
				let that = this;
				const chsData = this.authInfo;
				chsData.orderNumber = this.orderInfo.orderNumber;
				uni.navigateTo({
					url: '/hosp/chs/order?params=' + JSON.stringify(chsData)
				})
			},
			getPaySignData: function() {
				this.initData();
				let that = this;
				this.loading = true;
				this.show = false;
				this.dawnMsgBox = '';
				this.orderInfo = {};
				
				PayApi.paySignData(this.queryData).then(res => {
					console.table(res);
					this.loading = false;
					if (res.code === 0) {
						this.orderInfo = res.data;

						if (that.auth.retCode) {
							that.toChsOauthUser()
						}
					} else {
						this.show = true;
						this.msg = res.msg;
					}
				}).catch(err => {
					this.loading = false;
					this.show = true;
				})
			},
			onPay() {
				let that = this;
				this.show = false;
				this.showChs = false;
				this.dawnMsgBox = 'popup';
				this.msg = '';
				if (this.payType === 'PAY_WX_JSAIPI') {
					this.loading = true;
					const payData = new Object();
					payData.orderNumber = this.orderInfo.orderNumber;
					payData.signDataStr = this.orderInfo.signDataStr;
					payData.patientId = that.patientInfo.patientId;
					payData.patientName = that.patientInfo.name;
					PayApi.payWx(payData).then(res => {
						console.table(res);
						this.loading = false;
						if (res.code === 0) {
							that.wxpay(res.data);
						} else {
							this.show = true;
							this.msg = res.msg;
						}
					}).catch(err => {
						console.table(err);
						this.loading = false;
						this.show = true;
						this.msg = err.message;
					})
				} else if (this.payType === 'PAY_WX_CHS') {
					// console.table(this.chsPass);
					if (this.chsPass.id && this.chsPass.value !== 'open') {
						if (this.chsPass.value.indexOf(this.orderInfo.cardNo) !== -1) {
							this.toChsPay();
						} else {
							return this.$util.Tips({
								title: '功能正在调试...'
							});
						}
					} else {
						this.toChsPay();
					}
				}
			},
			toChsPay() {
				let urlData = location.pathname + "?orderNumber=" + this.queryData.orderNumber + "&openid=" + this
					.orderInfo.userId;
				this.showChs = true;
				chs.toOauth(urlData);
			},
			// 检测支付环境中的 WeixinJSBridge
			wxpay: function(data) {
				let that = this;
				if (typeof WeixinJSBridge == "undefined") {
					if (document.addEventListener) {
						document.addEventListener('WeixinJSBridgeReady', that.onBridgeReady(data), false);
					} else if (document.attachEvent) {
						document.attachEvent('WeixinJSBridgeReady', that.onBridgeReady(data));
						document.attachEvent('onWeixinJSBridgeReady', that.onBridgeReady(data));
					}
				} else {
					that.onBridgeReady(data);
				}
			},
			onBridgeReady: function(data) {
				let that = this;
				let appId = data.appId?data.appId:data.sub_appId;
				console.info(appId);
				WeixinJSBridge.invoke(
					'getBrandWCPayRequest', {
						// 传入第一步后端接口返回的核心参数
						"appId": appId, //公众号
						"timeStamp": data.timeStamp, //时间戳
						"nonceStr": data.nonceStr, //随机串
						"package": data.package, //prepay_id
						"signType": data.signType, //微信签名方式RSA
						"paySign": data.paySign //微信签名
					},
					function(res) {
						// 支付成功
						if (res.err_msg == "get_brand_wcpay_request:ok") {
							// 使用以上方式判断前端返回,微信团队郑重提示：
							//res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
							that.navReturn();
						} else if (res.err_msg == "get_brand_wcpay_request:cancel") {
							// 支付过程中用户取消
							that.show = true;
							that.msg = '用户取消支付';
						} else if (res.err_msg == "get_brand_wcpay_request:fail") {
							// 支付失败
							that.show = true;
							that.msg = '支付失败';
						} else {
							/**
							 * 其它
							 * 1、请检查预支付会话标识prepay_id是否已失效
							 * 2、请求的appid与下单接口的appid是否一致
							 * */
							that.show = true;
							that.msg = res.err_msg;
						}
					});
			},
			navReturn() {
				uni.navigateTo({
					url: '/hosp/order/return?orderNumber=' + this.orderInfo.orderNumber
				})
			},
			formatDate: function(date) {
				return dayjs(date).format("YYYY-MM-DD");
			},
			fen2yuan(price) {
				return Util.fen2yuan(price)
			},
			formatDateTime: function(date) {
				return dayjs(date).format("YYYY-MM-DD HH:mm:ss");
			}
		}
	}
</script>

<style lang="scss" scoped>
	.list-text {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 10rpx 0rpx !important;
		border-bottom: 1px solid $dawn-line-color;

		&__right {
			font-size: $dawn-font-size-md;
		}
	}

	.list-icon-text,
	.list-image-text {
		padding: 15rpx 20rpx;
		border-bottom: 1px solid #ece9ec;
	}

	.list {
		font-size: 14px;

		&__left {
			display: flex;
			align-items: center;
			justify-content: flex-start;

			&__icon,
			&__image {
				margin-right: 18rpx;
			}

			&__image {
				margin-right: 18rpx;
				width: 60rpx;
				height: 60rpx;
			}
		}

		&__right {
			display: flex;
			align-items: center;
			justify-content: flex-end;
		}
	}

	/* 卡 */
	.button-vip {
		width: 100%;
		height: 240rpx;
		border-radius: $dawn-border-radius;
		position: relative;
		z-index: 1;

		&::after {
			content: " ";
			position: absolute;
			z-index: -1;
			width: 100%;
			height: 100%;
			left: 0;
			bottom: 0;
			border-radius: inherit;
			opacity: 1;
			transform: scale(1, 1);
			background-size: 100% 100%;
		}
	}
</style>